package luluinner;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

import luluinner.config.ConfigMaster;
import luluinner.msg.upper.OuterMsgServer;
import luluinner.util.Constants;

public class StartUp {

    public static void main(String[] args) {

        String pigeonCode = getPigeonCode();
        if (args != null && args.length > 0) {
            pigeonCode += "|" + args[0];
        }

        ConfigMaster configLoad = ConfigMaster.getInstance();
        configLoad.init();

        configLoad.setPigeonCode(pigeonCode);

        Map<String, Object> configs = configLoad.getConfigs();

        String outer_ip = (String) configs.get(Constants.OUTER_IP_KEY);
        int outer_msg_port = (Integer) configs.get(Constants.OUTER_MSG_PORT_KEY);
        int outer_data_port = (Integer) configs.get(Constants.OUTER_DATA_PORT_KEY);

        System.out.println("OuterMsgMaster.begin:" + configs);
        OuterMsgServer outerMsgServer = new OuterMsgServer(outer_ip, outer_msg_port, pigeonCode, outer_data_port);

        outerMsgServer.init();
    }

    private static String getPigeonCode() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        StringBuilder sb = new StringBuilder();
                        sb.append(ip);

                        byte[] mac = networkInterface.getHardwareAddress();
                        if (Objects.nonNull(mac)) {
                            sb.append('|');
                            for (int i = 0; i < mac.length; i++) {
                                sb.append(String.format("%02X", mac[i]));
                            }
                        }
                        System.out.println(sb);
                        return sb.toString();
                    }
                }

            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }
}
